import { _decorator, Component, Node, resources } from 'cc';
import { csvManager } from './csvManager';
import { resourceUtil } from './resourceUtil';
const { ccclass, property } = _decorator;


@ccclass('localConfig')
export class localConfig extends Component {
    private static _instance: localConfig;
    private _csvManager: csvManager = new csvManager();

    static get instance() {
        if (this._instance) {
            return this._instance;
        }

        this._instance = new localConfig();
        return this._instance;
    }



    private _callback: Function = new Function();
    private _cntLoad: number = 0;
    private _currentLoad: number = 0;

    /**
     * 加载配置文件
     * @param {Function}cb 回调函数 
     */
    public loadConfig(cb: Function) {
        this._callback = cb;
        this._loadCSV();
    }

    private _loadCSV() {
        //新增数据表 请往该数组中添加....
        resources.loadDir("datas", (err: any, assets) => {
            if (err) {
                return;
            }

            let arrCsvFiles = assets.filter((item: any) => {
                return item._native !== ".md";
            })

            this._cntLoad = arrCsvFiles.length;

            //客户端加载
            if (arrCsvFiles.length) {
                arrCsvFiles.forEach((item, index, array) => {
                    resourceUtil.getTextData(item.name, (err: any, content: any) => {
                        this._csvManager.addTable(item.name, content);
                        this._tryToCallbackOnFinished();
                    });
                });
            } else {
                this._tryToCallbackOnFinished();
            }
        })
    }

    /**
     * 根据ID查询一条表内容
     * @param {string}tableName 表名
     * @param {string}ID
     * @returns {Object} 一条表内容
     */
    queryByID(tableName: string, ID: string) {
        return this._csvManager.queryByID(tableName, ID);
    }


    getTableArr(tableName: string) {
        return this._csvManager.getTableArr(tableName);
    }

    private _tryToCallbackOnFinished () {
        if (this._callback) {
            this._currentLoad++;
            if (this._currentLoad >= this._cntLoad) {
                this._callback();
            }
        }
    }
}


